import axios from 'axios'
const service = axios.create({
    baseURL: '/',
    timeout: 5 * 1000
})
const EXPIRE_TIME = 5 * 1000
const cacheMap = {}
const controller = new AbortController()
service.interceptors.request.use(config => {
    const {cache, url} = config
    if (cache) {
        config.signal = controller.signal
        if (cacheMap[url] && Date.now() < (cacheMap[url].timestamp + EXPIRE_TIME)) {
            controller.abort()
        }
    }
    return config
})
service.interceptors.response.use(response => {
    const {config: { cache, url }, data} = response
    if (cache) {
        cacheMap[url] = {
            data,
            timestamp: Date.now()
        }
    }
    return response
}, error => {
    if (axios.isCancel(error)) return Promise.resolve(cacheMap[error.config.url].data)
    return Promise.reject(error)
})
export default service
